<template>
  <el-card class="form-card">
    <template #header>
      <div class="card-header">
        <span>队伍信息</span>
      </div>
    </template>
    <div class="form-content">
      <el-form :model="teamForm" size="large" :rules="teamRules" ref="teamFormRef" label-width="100px" label-position="top">
        <!-- 已选成员 -->
        <el-form-item label="已选成员">
          <div class="selected-members">
            <el-empty v-if="selectedStudents.length === 0" description="还没有选择队员" :image-size="80" />
            <div v-else class="member-list">
              <div v-for="student in selectedStudents" :key="student.studentId" class="member-item">
                <div class="member-info">
                  <span class="member-name">{{ student.user?.nickName || student.nickName || '未知' }}</span>
                  <span class="member-number">{{ student.stuId || '-' }}</span>
                </div>
                <div class="member-actions">
                  <el-radio-group v-model="teamForm.leaderId" size="small">
                    <el-radio :label="student.studentId" border>队长</el-radio>
                  </el-radio-group>
                  <el-button link type="danger" size="small" icon="Close" @click="handleUnselectStudent(student.studentId)" />
                </div>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-divider />

        <!-- 毕设名称 -->
        <el-form-item label="毕设名称" prop="teamName">
          <el-input v-model="teamForm.teamName" placeholder="请输入毕设名称" />
        </el-form-item>

        <!-- 毕设简介 -->
        <el-form-item label="毕设简介" prop="summary">
          <el-input v-model="teamForm.summary" type="textarea" :rows="4" placeholder="请输入毕设简介" />
        </el-form-item>

        <!-- 动态教师志愿 -->
        <div v-for="(item, index) in teacherVolunteerSlots" :key="index">
          <el-form-item :label="`第${index + 1}志愿`" :prop="`teacherVolunteer${index + 1}`">
            <el-select v-model="teamForm.teacherVolunteers[index]" placeholder="请选择志愿教师" clearable style="width: 100%" :loading="teacherLoading">
              <el-option v-for="teacher in getAvailableTeachers(index)" :key="teacher.userId" :label="teacher.user.nickName" :value="teacher.teacherId" />
            </el-select>
          </el-form-item>
        </div>
        <div v-if="teacherVolunteerSlots.length > 0" class="form-tip">请按优先级依次选择志愿教师，最多可选择 {{ groupInfo.teacherMax || 0 }} 个</div>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting" style="width: 100%; margin-top: 20px">{{ isEdit ? '保存修改' : '创建队伍' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, watch, getCurrentInstance } from 'vue'

const props = defineProps({
  selectedStudents: {
    type: Array,
    default: () => []
  },
  teacherList: {
    type: Array,
    default: () => []
  },
  teacherLoading: {
    type: Boolean,
    default: false
  },
  groupInfo: {
    type: Object,
    default: () => ({})
  },
  groupId: {
    type: String,
    required: true
  },
  deptId: {
    type: String,
    required: true
  },
  gradeId: {
    type: String,
    required: true
  },
  submitting: {
    type: Boolean,
    default: false
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['unselect-student', 'submit'])

const { proxy } = getCurrentInstance()

// 队伍表单
const teamFormRef = ref(null)
const teamForm = ref({
  groupId: props.groupId,
  deptId: props.deptId,
  gradeId: props.gradeId,
  teamName: '',
  summary: '',
  teacherVolunteers: [],
  leaderId: null
})

const teamRules = ref({
  teamName: [{ required: true, message: '请输入毕设名称', trigger: 'blur' }]
})

// 动态生成教师志愿槽位
const teacherVolunteerSlots = computed(() => {
  const max = props.groupInfo.teacherMax || 0
  return Array.from({ length: max }, (_, i) => i)
})

// 获取可用的教师列表（排除已选择的教师）
const getAvailableTeachers = (currentIndex) => {
  return props.teacherList.filter((teacher) => {
    if (teamForm.value.teacherVolunteers[currentIndex] === teacher.teacherId) {
      return true
    }
    // 排除其他志愿已选择的教师
    return !teamForm.value.teacherVolunteers.includes(teacher.teacherId)
  })
}

// 取消选择学生
const handleUnselectStudent = (studentId) => {
  emit('unselect-student', studentId)
  // 如果取消的是队长，清空队长选择
  if (teamForm.value.leaderId === studentId) {
    teamForm.value.leaderId = null
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!teamFormRef.value) return

  // 验证是否选择了队员
  if (props.selectedStudents.length === 0) {
    proxy.$modal.msgError('请至少选择一名队员')
    return
  }

  // 验证是否选择了队长
  if (!teamForm.value.leaderId) {
    proxy.$modal.msgError('请在已选队员中指定队长')
    return
  }

  // 验证队伍人数
  const teamMax = props.groupInfo.teamMax || 0
  if (teamMax > 0 && props.selectedStudents.length > teamMax) {
    proxy.$modal.msgError(`队伍人数不能超过 ${teamMax} 人`)
    return
  }

  try {
    await teamFormRef.value.validate()

    // 组装学生数据
    const students = props.selectedStudents.map((student) => ({
      studentId: student.studentId,
      isLeader: student.studentId === teamForm.value.leaderId ? '1' : '0'
    }))

    // 过滤掉空的教师志愿，并转换为字符串
    const teacherVolunteers = teamForm.value.teacherVolunteers.filter((id) => id !== null && id !== undefined && id !== '').join(',')

    // 组装提交数据
    const payload = {
      ...teamForm.value,
      students,
      teacherVolunteers
    }

    emit('submit', payload)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单（暴露给父组件）
const resetForm = () => {
  // 重置表单验证状态
  teamFormRef.value?.resetFields()

  // 清空表单数据
  teamForm.value = {
    groupId: props.groupId,
    deptId: props.deptId,
    gradeId: props.gradeId,
    teamName: '',
    summary: '',
    teacherVolunteers: [],
    leaderId: null
  }
}

// 监听 props 变化更新表单
watch(
  () => [props.groupId, props.deptId, props.gradeId],
  ([newGroupId, newDeptId, newGradeId]) => {
    teamForm.value.groupId = newGroupId
    teamForm.value.deptId = newDeptId
    teamForm.value.gradeId = newGradeId
  }
)

// 填充表单数据（编辑模式）
const fillFormData = (data) => {
  teamForm.value.teamName = data.teamName || ''
  teamForm.value.summary = data.summary || ''
  teamForm.value.leaderId = data.leaderId || null
  teamForm.value.teacherVolunteers = [...(data.teacherVolunteers || [])]
}

// 暴露方法给父组件
defineExpose({
  resetForm,
  fillFormData
})
</script>

<style scoped>
.form-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.form-card :deep(.el-card__body) {
  flex: 1;
  overflow: hidden;
}

.form-content {
  height: 100%;
  overflow: auto;
}

.form-content::-webkit-scrollbar {
  display: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: var(--el-color-primary);
  font-size: 24px;
  flex-shrink: 0;
}

/* 已选成员样式 */
.selected-members {
  width: 100%;
  min-height: 120px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 12px;
  background-color: #fafafa;
}

.member-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.member-item:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.member-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.member-name {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
}

.member-number {
  font-size: 12px;
  color: #909399;
}

.member-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
